using System;
using System.Diagnostics.Contracts;
using System.Linq.Expressions;
using System.Reflection;

namespace Sundstrom.Mvvm
{
    public static class ExtendedViewModelExtensions
    {
        /// <summary>
        /// Validates a property.
        /// </summary>
        /// <param name="propertyExpression">An expression for a property.</param>
        /// <typeparam name="TViewModel">A ViewModel.</typeparam>
        /// <typeparam name="TProperty">The type of the property in the expression.</typeparam>
        public static void ValidateProperty<TViewModel, TProperty>(this TViewModel viewModel, Expression<Func<TViewModel, TProperty>> propertyExpression)
            where TViewModel : ExtendedViewModelBase
        {
            Contract.Requires<ArgumentException>(propertyExpression != null);

            var body = propertyExpression.Body;
            var memberExpression = body as MemberExpression;
            if (memberExpression != null && memberExpression.Member is PropertyInfo)
            {
                var member = memberExpression.Member;
                try
                {
                    viewModel.ValidateProperty(member.Name);
                }
                catch (ArgumentException e)
                {
                    throw new ArgumentException(e.Message, "propertyExpression");
                }
            }
            else
            {
                throw new ArgumentException(ObservableObject.PropertyExpressionExpected, "propertyExpression");
            }
        }

    }
}